import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';

/**
 * 验证码服务
 * 基于 NestJS 官方示例实现
 * 参考: https://docs.nestjs.cn/fundamentals/dependency-injection
 * 对应 Java: CaptchaUtils
 */
@Injectable()
export class CaptchaService {
  /**
   * 生成图片验证码
   */
  generate(options?: svgCaptcha.ConfigObject): svgCaptcha.CaptchaObj {
    return svgCaptcha.create(options);
  }

  /**
   * 生成数学验证码
   */
  generateMath(options?: svgCaptcha.ConfigObject): svgCaptcha.CaptchaObj {
    return svgCaptcha.createMathExpr(options);
  }

  /**
   * 生成简单验证码
   */
  generateSimple(options?: svgCaptcha.ConfigObject): svgCaptcha.CaptchaObj {
    return svgCaptcha.create({
      size: 4,
      ignoreChars: '0o1il',
      noise: 1,
      color: true,
      background: '#f0f0f0',
      ...options,
    });
  }

  /**
   * 生成复杂验证码
   */
  generateComplex(options?: svgCaptcha.ConfigObject): svgCaptcha.CaptchaObj {
    return svgCaptcha.create({
      size: 6,
      noise: 3,
      color: true,
      background: '#f0f0f0',
      fontSize: 50,
      width: 150,
      height: 50,
      ...options,
    });
  }

  /**
   * 验证验证码
   */
  verify(
    input: string,
    captcha: string,
    caseSensitive: boolean = false,
  ): boolean {
    if (caseSensitive) {
      return input === captcha;
    }
    return input.toLowerCase() === captcha.toLowerCase();
  }
}
